<template>
  <el-select
    style="width: 100%"
    :multiple="config.multiple"
    clearable
    filterable
    :placeholder="placeholder"
    v-model="selected"
    @change="select"
    @clear="clear"
  >
    <el-option v-for="item in dataList" :key="item[config.value]" :label="item[config.label]" :value="item[config.value]" />
  </el-select>
</template>

<script setup lang="ts" name="selectFilter">
import { computed, onMounted, ref } from "vue";
import { useDataStore } from "@/stores/modules/data";

interface ConfigProps {
  value: string;
  label: string;
  multiple?: boolean;
}

interface SelectFilterProps {
  dataKey?: string;
  requestApi?: (params: any) => Promise<any>; // 请求表格数据的 api ==> 非必传
  data?: OptionsProps[]; // 选择的列表数据
  value?: String;
  config?: ConfigProps;
  placeholder?: String;
}

const props = withDefaults(defineProps<SelectFilterProps>(), {
  placeholder: () => "请选择",
  config: () => ({ label: "name", value: "value", multiple: false })
});

interface OptionsProps {
  value: string;
  name: string;
}

const dataStore = useDataStore();
const selected = ref();
const dataList: any = computed(() => {
  if (props.data && props.data.length > 0) {
    return props.data;
  } else {
    if (props.dataKey) {
      return dataStore.getCommonDataByName(props.dataKey);
    } else {
      return [];
    }
  }
});
// watch(dataList, () => {
//   if (dataList.value) {
//     const selectValue = dataList.value.find(item => item._id === props.value);
//     if (selectValue) {
//       selected.value = selectValue._id;
//     }
//   }
// });

onMounted(async () => {
  if (props.dataKey) {
    await dataStore.findList(props.dataKey, props.requestApi);
  }
  selected.value = props.value;
});

const select = () => {
  emit("change", selected.value);
};

const clear = () => {
  emit("clear");
};

// emit
const emit = defineEmits<{
  change: [value: any];
  clear;
}>();
</script>

<style scoped lang="scss"></style>
